package info.wegosoft.android.adapter;

import info.wegosoft.R;
import info.wegosoft.android.activity.MBlogPlatformListActivity;
import info.wegosoft.android.model.Platform;
import info.wegosoft.android.qauth.sina.OAuthConstant;
import info.wegosoft.android.qauth.sina.Weibo;
import info.wegosoft.android.qauth.sina.WeiboException;
import info.wegosoft.android.qauth.sina.http.RequestToken;
import info.wegosoft.android.qauth.tencent.OAuth;
import info.wegosoft.android.qauth.tencent.QWeiboSyncApi;
import info.wegosoft.android.qauth.tencent.QWeiboType.ResultType;
import info.wegosoft.android.util.CacheUtil;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


/**  
 * Filename:    PlatformAdapter.java 
 * Package:     info.wegosoft.android.adapter 
 * Description: TODO(这里用一句话描述这个类的作用)
 * Copyright:   Copyright (c) wegosoft.info 2011  
 * @author:     李辉 
 * email:       fzlihui@gmail.com
 * @version:    1.0  
 * Create at:   2011-5-18 下午10:53:20  
 */
public class PlatformAdapter extends ArrayAdapter<Platform> {

	//人人登录所需
	
//	private String apiKey = "6080c66e57eb44b58a2830adc6ab46d1";
//
//    Renren renren;
//
//    AsyncRenren asyncRenren;
//
//    SimpleRequestListener simpleRequestListener;
    
	private int resource;
	
	MBlogPlatformListActivity weiboPlatformListActivity;
	//添加用户qauth时的进度条
	private ProgressDialog addUserProgressDialog;
	
	public PlatformAdapter(Context context, int resource,
			List<Platform> platformList) {
		
		super(context, resource, platformList);
		
		this.resource = resource;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		LinearLayout ll;
		
		if (convertView == null) {
			
			ll = new LinearLayout(getContext());

			String inflater = Context.LAYOUT_INFLATER_SERVICE;

			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(inflater);

			vi.inflate(resource, ll, true);

		} else {
			
			ll = (LinearLayout) convertView;
			
		}
		
		Platform platform = getItem(position);
		
		ImageView imageView = (ImageView) ll.findViewById(R.id.platformLogo);
		
		imageView.setImageResource(platform.getPlatformLogoResourceId());
		
		TextView textView = (TextView) ll.findViewById(R.id.use_status);
		
		textView.setText("尚未使用");
		
		Button addUserBtn = (Button) ll.findViewById(R.id.addUserBtn);
        
		Button enterBtn = (Button) ll.findViewById(R.id.enterBtn);
		
		Button delUserBtn = (Button) ll.findViewById(R.id.delUserBtn);
		
		switch (platform.getPlatFormType()) {
			case Platform.SINA_PLATFORM:
				
				 setSinaItem(addUserBtn,enterBtn,delUserBtn,textView);
				
				 break;
			case Platform.TENCENT_PLATFORM:
				
				 setTencentItem(addUserBtn,enterBtn,delUserBtn,textView);
				 
				 break;	
			case Platform.RENREN_PLATFORM:
				
				setRenrenItem(addUserBtn,enterBtn,delUserBtn,textView);
				
				break;
			default:
				 break;
		}
		
		return ll;
	}
	
	/**
	 * 设置腾讯行
	 */
	private void setTencentItem(Button addUserBtn,Button enterBtn,Button delUserBtn,TextView userStatusTextView){
		
		SharedPreferences preference = getContext().getSharedPreferences("tencent_qauth",Context.MODE_PRIVATE);
		 
		String accessToken = preference.getString("AccessToken", null);
		
		//未使用
		if(accessToken == null){
			 enterBtn.setVisibility(View.GONE);
			 
			 delUserBtn.setVisibility(View.GONE);
			 
			 addUserBtn.setVisibility(View.VISIBLE);
			 
			 //添加用户按钮事件
			 addUserBtn.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
	
					LayoutInflater inflater = LayoutInflater.from(getContext());
					
			        final View layout = inflater.inflate(R.layout.tencent_pin_dialog,null);
			        
			        //以下qauth流程说明见http://open.t.qq.com/resource.php?i=1,2
					new AlertDialog.Builder(getContext()).setView(layout).setNegativeButton("返回",null).setPositiveButton("确定", new DialogInterface.OnClickListener() {
						 
						public void onClick(DialogInterface dialog, int which) {
							
								EditText pinEditText = (EditText) layout.findViewById(R.id.pinEditText);
								
								QWeiboSyncApi api = new QWeiboSyncApi();
								
//								System.out.println("!!!" + pinEditText.getText().toString());
								
								String resStr = api.getAccessToken(OAuth.AppKey, OAuth.AppSecret, OAuth.TokenKey,OAuth.TokenSecret, pinEditText.getText().toString());
								
//								System.out.println(resStr);
								
								//使用授权后的Request Token换取Access Token，返回oauth_token和oauth_token_secreate
								OAuth.parseToken(resStr);
								
								String userInfo = api.getSelfInfo(OAuth.AppKey, OAuth.AppSecret, OAuth.TokenKey,OAuth.TokenSecret, ResultType.ResultType_Json);
								
								String userName = "";
								try {
									//返回数据格式见http://open.t.qq.com/resource.php?i=1,1
									JSONObject jsonObject = new JSONObject(userInfo);
									
//									System.out.println(jsonObject.getJSONObject("data").getString("name"));
									
									userName = jsonObject.getJSONObject("data").getString("name");
								} catch (JSONException e) {
									e.printStackTrace();
								}
//								System.out.println(userInfo);
								
								SharedPreferences preference = getContext().getSharedPreferences("tencent_qauth",Context.MODE_PRIVATE);
								
								Editor editor = preference.edit();
								
								editor.putString("AccessToken", OAuth.TokenKey);
								
								editor.putString("AccessTokenSecret", OAuth.TokenSecret);
								
								editor.putString("userName", userName);
								
								editor.commit();
								
								Intent intent = new Intent(getContext(),MBlogPlatformListActivity.class);
								
								getContext().startActivity(intent);
						}
					}).show();
					
					
					
					new Thread()
				    { 
				        public void run()
				        { 
							QWeiboSyncApi api = new QWeiboSyncApi();
							
							String response = api.getRequestToken(OAuth.AppKey, OAuth.AppSecret);
							
//							System.out.println(response);
							
							//获取未授权的Request Token
							//返回oauth_token=0b425b155bf84afba25b0839d652a4df&oauth_token_secret=01f26ecc9ed90395653a7e774fd9c873&oauth_callback_confirmed=true
							OAuth.parseToken(response);
							
							Uri uri = Uri.parse("http://open.t.qq.com/cgi-bin/authorize?oauth_token=" + OAuth.TokenKey);
							
							getContext().startActivity(new Intent(Intent.ACTION_VIEW, uri));
							
				        }
				    }.start(); 	
				}
			 });
			 
		}else{//已添加账户
			 userStatusTextView.setText(preference.getString("userName", "")); 

			 enterBtn.setVisibility(View.VISIBLE);
			 
			 delUserBtn.setVisibility(View.VISIBLE);
			 
			 addUserBtn.setVisibility(View.GONE);
			 
			 //进入微博按钮事件
			 enterBtn.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
			        	 
						SharedPreferences preference = getContext().getSharedPreferences("platform",Context.MODE_PRIVATE);

				        Editor edit = preference.edit();
							         
						edit.putInt("type",Platform.TENCENT_PLATFORM);
						
						edit.commit();
						
						MBlogPlatformListActivity weiboPlatformListActivity = (MBlogPlatformListActivity) getContext();
						
						weiboPlatformListActivity.loadCache();
					}
				 });
			 
			 //删除用户按钮事件
			 delUserBtn.setOnClickListener(new OnClickListener(){
				public void onClick(View v) {
					
					new AlertDialog.Builder(getContext())
					.setTitle("真的要删除该账户？")
					.setMessage("确定要删除该账户?")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									SharedPreferences preference = getContext().getSharedPreferences("platform",Context.MODE_PRIVATE);

							        Editor editor = preference.edit();
										         
							        editor.putInt("type",-1);
									
							        editor.commit();
							        
							        SharedPreferences preference2 = getContext().getSharedPreferences("tencent_qauth",Context.MODE_PRIVATE);
							        
							        Editor editor2 = preference2.edit();
							        
							        editor2.putString("AccessToken", null);
									
							        editor2.putString("AccessTokenSecret", null);
									
							        editor2.putString("userName", null);
									
							        editor2.commit();
									
							        //清除本地缓存
							        CacheUtil.cleanLocalCache(getContext(), Platform.TENCENT_PLATFORM);
							        
									Intent intent = new Intent();
									
									intent.setClass(getContext(), MBlogPlatformListActivity.class);
									
									getContext().startActivity(intent);
								}
							}).setNegativeButton("取消", null).show();
					
					
				} 
				
					
				});
		}
	}
	
	/**
	 *  设置新浪行
	 */
	private void setSinaItem(Button addUserBtn,Button enterBtn,Button delUserBtn,TextView userStatusTextView){
		 
		 SharedPreferences preference = getContext().getSharedPreferences("sina_qauth",Context.MODE_PRIVATE);
		 
		 String accessToken = preference.getString("AccessToken", null);
		 //未使用
		 if(accessToken == null){
			 
			 enterBtn.setVisibility(View.GONE);
			 
			 delUserBtn.setVisibility(View.GONE);
			 
			 addUserBtn.setVisibility(View.VISIBLE);
			 
			 //添加用户按钮事件
			 addUserBtn.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					//显示Progress对话框
					addUserProgressDialog = ProgressDialog.show(getContext(),null,"加载中",true);
					new Thread()
				    { 
				        public void run()
				        { 
				        	System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
					    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
					    	Weibo weibo = OAuthConstant.getInstance().getWeibo();
			            	RequestToken requestToken;
							try {
								requestToken = weibo.getOAuthRequestToken("wegoandroid://MBlogPlatformListActivity");
				    			Uri uri = Uri.parse(requestToken.getAuthenticationURL()+ "&from=xweibo");
				    			OAuthConstant.getInstance().setRequestToken(requestToken);
				    			getContext().startActivity(new Intent(Intent.ACTION_VIEW, uri));
							} catch (WeiboException e) {
								e.printStackTrace();
							}  
				        }
				    }.start(); //开始运行运行线程 			
				}
			 });
			 
		 }else{//已经获取了accessToken
			 
			 userStatusTextView.setText(preference.getString("userName", "")); 

			 enterBtn.setVisibility(View.VISIBLE);
			 
			 delUserBtn.setVisibility(View.VISIBLE);
			 
			 addUserBtn.setVisibility(View.GONE);
			 
			 //进入微博按钮事件
			 enterBtn.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
						 
			        	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
			        	 
						SharedPreferences preference = getContext().getSharedPreferences("platform",Context.MODE_PRIVATE);

				        Editor edit = preference.edit();
							         
						edit.putInt("type",Platform.SINA_PLATFORM);
						
						edit.commit();
						
						SharedPreferences preference2 = getContext().getSharedPreferences("sina_qauth",Context.MODE_PRIVATE);
							
						Weibo weibo = new Weibo();
						
						weibo.setToken(preference2.getString("AccessToken", null), preference2.getString("AccessTokenSecret", null));
						
						OAuthConstant.getInstance().setWeibo(weibo);
						
						MBlogPlatformListActivity weiboPlatformListActivity = (MBlogPlatformListActivity) getContext();
						
						weiboPlatformListActivity.loadCache();
					}
				 });
			 
			 //删除用户按钮事件
			 delUserBtn.setOnClickListener(new OnClickListener(){

				 public void onClick(View v) {
					
					new AlertDialog.Builder(getContext())
					.setTitle("真的要删除该账户？")
					.setMessage("确定要删除该账户?")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									SharedPreferences preference = getContext().getSharedPreferences("platform",Context.MODE_PRIVATE);

							        Editor editor = preference.edit();
										         
							        editor.putInt("type",-1);
									
							        editor.commit();
							        
							        SharedPreferences preference2 = getContext().getSharedPreferences("sina_qauth",Context.MODE_PRIVATE);
							        
							        Editor editor2 = preference2.edit();
							        
							        editor2.putString("AccessToken", null);
									
							        editor2.putString("AccessTokenSecret", null);
									
							        editor2.putString("userName", null);
									
							        editor2.commit();
									
							        //清除本地缓存
							        CacheUtil.cleanLocalCache(getContext(), Platform.SINA_PLATFORM);
							        
									Intent intent = new Intent();
									
									intent.setClass(getContext(), MBlogPlatformListActivity.class);
									
									getContext().startActivity(intent);
								}
							}).setNegativeButton("取消", null).show();
					
					
				} 
			 });
		 }

	}
	
	/**
	 * @param addUserBtn
	 * @param enterBtn
	 * @param delUserBtn
	 * @param userStatusTextView
	 * 设置校内行
	 */
	private void setRenrenItem(Button addUserBtn,Button enterBtn,Button delUserBtn,TextView userStatusTextView){ 
		
		addUserBtn.setVisibility(View.VISIBLE);
		
		addUserBtn.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
//				renren = new Renren(apiKey);
//		        renren.restorSessionKey(getContext());
//		        asyncRenren = new AsyncRenren(renren);
//		        RenrenAuthListener listener = new SimpleRenrenAuthListener(PlatformAdapter.this, "User Agent Flow");
//	            String [] permissions = {"publish_blog","photo_upload","publish_feed","status_update"};
//	            renren.authorize(RecentActivityUtil.recentActivity,permissions, listener);
			}
			
		});
	}
}
